package com.zhongke.cotrun.service.impl;

import com.google.gson.Gson;
import com.zhongke.cotrun.mapper.WxSysDictMapper;
import com.zhongke.cotrun.model.pojo.WxSysDict;
import com.zhongke.cotrun.service.WxSysDictService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class WxSysDictServiceImpl implements WxSysDictService {

    @Autowired
    WxSysDictMapper wxSysDictMapper;
    
    @Autowired
    RedisTemplate<String,Object> redisTemplate;
    
   /**
     * 获取需求类型列表
	 *
	 * @param userId
	 * @return
	 */
    @Cacheable(cacheNames="wxSysDict",key="'wxSysDict-'+#type")
	public List<WxSysDict> selectAllType(String type){
		return wxSysDictMapper.selectAll(type);
	}
	/**
	 * 获取指定类指定标签
	 * @param value
	 * @param type
	 * @param defaultValue
	 * @return
	 */
	public String getDictLabel(String value, String type, String defaultValue){
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(value)){
			
			ValueOperations<String, Object> vo = redisTemplate.opsForValue();
			
			Object obj =  vo.get("wxSysDict-"+type);
			List<WxSysDict> list = new ArrayList();
			Gson gson = new Gson();
			if(obj == null)
			{
				list = selectAllType(type);
				vo.set("wxSysDict-"+type, gson.toJson(list));		        
				obj =  vo.get("wxSysDict-"+type);
			}
			list = gson.fromJson(String.valueOf(obj), List.class);
			for (int i=0;i<list.size();i++){
				Map map = (Map)list.get(i);
				
				if (type.equals(map.get("type")) && value.equals(map.get("value"))){
					return String.valueOf(map.get("label"));
				}
			}
		}
		return defaultValue;
	}
	
}
